package com.mobzilla.service;

import com.google.gson.Gson;
import com.mobzilla.model.Bug;
import com.mobzilla.model.Status;
import com.mobzilla.util.Constants;
import com.mobzilla.util.Lock;

public class UpdateServiceImpl implements UpdateService {

	private static final String URL_PREFIX = Constants.BASE_URL + "/bug/";

	private static final String STR_UPDATE_STATUS = "{\"status\":\"$$status$$\",\"update_token\":\"$$token$$\"}";

	@Override
	public boolean updateStatus(Status status, int bugId, String userName,
			String password) {
		if (status == null || bugId <= 0 || userName == null
				|| password == null) {
			return false;
		}
		StringBuilder builder = new StringBuilder(URL_PREFIX);
		builder.append(bugId).append("?username=").append(userName);
		builder.append("&password=").append(password);

		String url = builder.toString();
		Bug bug = processForBean(url);

		String updateLine = "";

		if (status.equals(Status.RESOLVED)) {
			updateLine = STR_UPDATE_STATUS.replace("$$status$$",
					status.getValue()+"\",\"resolution\":\"FIXED");
		} else {
			updateLine = STR_UPDATE_STATUS.replace("$$status$$",
					status.getValue());
		}

		updateLine = updateLine.replace("$$token$$", bug.getUpdateToken());

		return updateBean(url, updateLine);

	}

	private boolean updateBean(String url, String updateLine) {
		Lock<String> lock = new Lock<String>();
		HTTPRequestPutAsync putAsync = new HTTPRequestPutAsync(url, lock,
				updateLine);
		putAsync.execute();

		while (!lock.isDataSet()) {
			// Do Nothing
		}

		if (lock.getData() == null) {
			return false;
		}
		return true;
	}

	private Bug processForBean(String url) {
		Lock<String> lock = new Lock<String>();
		HTTPRequestAsync async = new HTTPRequestAsync(url, lock);
		async.execute();

		while (!lock.isDataSet()) {
			// Do Nothing
		}

		if (lock.getData() == null) {
			return null;
		}

		Gson gson = new Gson();
		Bug response = gson.fromJson(lock.getData(), Bug.class);

		if (response == null) {
			return null;
		}
		return response;
	}

}
